package XZK010203AND001;

/**
 * @author bing.z 2021/5/28 20:27
 **/
public class MyList {
    private Object[] element;
    private int size;

    public MyList(int cap) {
        if (cap < 0) {
            System.out.println("容量不能小于 0！");
            return;
        }
        element = new Object[cap];
    }

    // 1.增加方法
    public boolean add(Object el) {
        if (size == element.length) {
            growth();
        }
        element[size++] = el;
        return true;
    }

    private void growth() {
        // 数组扩容两倍
        Object[] newElemet = new Object[size * 2];
        System.arraycopy(element, 0, newElemet, 0, size);
        element = newElemet;
    }

    // 2.删除方法
    public boolean remove(int index) {
        if (index < 0 || index >= size) {
            System.out.println("数组下标越界！");
            return false;
        }
        if (size > 1) {
            System.arraycopy(element, index + 1, element, index, size - index - 1);
        }
        element[size - 1] = null;
        size--;
        return true;
    }

    public boolean remove(Object object) {
        int index = -1;
        for (int i = 0; i < element.length; i++) {
            if (element[i] == object) {
                index = i;
                break;
            }
        }
        if (index == -1) {
            System.out.println("未找到可删除的元素！");
            return false;
        }
        // 调用下标定位删除方法
        remove(index);
        return false;
    }

    // 3.查询方法
    public Object get(int index) {
        if (index < 0 || index >= size) {
            System.out.println("数组下标越界！");
            return null;
        }
        return element[index];
    }

    // 4.获取当前存储的有效数据长度
    public int size() {
        return size;
    }
}
